package org.icec.web.core.support.websocket;

import java.util.Map;

import javax.servlet.http.HttpSession;

import org.icec.common.constants.SessionConstants;
import org.icec.web.core.sys.model.SysUser;
import org.icec.web.core.sys.utils.ShiroKit;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;


/**
 * 握手前后的拦截，这里没有处理，默认
 *
 */
public class WebSocketHandshakeInterceptor extends HttpSessionHandshakeInterceptor {

	@Override
	public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
			Exception ex) {
		super.afterHandshake(request, response, wsHandler, ex);
	}

	@Override
	public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
			Map<String, Object> attributes) throws Exception {
		// 解决The extension [x-webkit-deflate-frame] is not supported问题
		if (request.getHeaders().containsKey("Sec-WebSocket-Extensions")) {
			request.getHeaders().set("Sec-WebSocket-Extensions", "permessage-deflate");
		}
		// 检查session的值是否存在
		if (request instanceof ServletServerHttpRequest) {
			ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
			HttpSession session = servletRequest.getServletRequest().getSession(false);
			SysUser user = ShiroKit.getUser();
			if (user != null) {
				Integer accountId = user.getId();
				// 把session和accountId存放起来
				attributes.put(SessionConstants.SESSIONID, session.getId());
				attributes.put(SessionConstants.SESSION_USERID, accountId);
			}
		}
		return super.beforeHandshake(request, response, wsHandler, attributes);
	}
}
